package com.xin.di.uav.applet.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xin.di.uav.applet.service.WxAppletService;
import com.xin.di.uav.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LTQ
 */
@Service
public class WxAppletServiceImpl implements WxAppletService {
    private final static Logger logger = LoggerFactory.getLogger(WxAppletServiceImpl.class);

    @Value("${proxy-url:sfproxy.intsit.sfcloud.local}")
    private String proxyUrl;

    @Value("${new-proxy-url:IE-UOCS-CORE-3adm832e.lbsit.sfcloud.local}")
    private String xcyProxyUrl;


    @Value("${is-use-proxy:false}")
    private boolean isUseProxy;

    @Value("${split-address.ak:b5b6eaed901242739c36771a6a9dab92}")
    private String splitAddressAk;

    @Value("${syscode:IE-UOCS-CORE}")
    private String syscode;


    @Value("${split-address.url:http://ftkj-gis-apis.intsit.sfcloud.local:1080/pai/api/addressidentify}")
    private String splitAddressUrl;

    @Value("${wx.miniprogram_state:developer}")
    private String miniprogramState;

    @Value("${h5.url:https://ie-uocs-out.sit.sf-express.com:4433/uocs-intracity/}")
    private String h5Url;

    @Autowired
    private RestTemplate restTemplate;


    @Value("${cloud.test_url: https://sit-xcy-gateway.jrit.top}")
    private String cloudTestUrl;

    @Value("${cloud.project_id: 301}")
    private String cloudProjectId;

    @Value("${cloud.key:35596947354c326a}")
    private String cloudKey;

    @Value("${test-pre-url:http://ie-uocs-int-apis.int.sfcloud.local:8000/}")
    private String testPreUrl;

    @Value("${callback.url:https://ie-uocs-out.sit.sf-express.com:4433/uocs-intracity/}")
    private String callbackUrl;

    /**
     * 发送订阅消息
     */
    @Override
    public void subscribeSend(String accessToken, String templateId, String openId, HashMap data, String pageUrl) {
        Map map = new HashMap();
        map.put("template_id", templateId);
        //点击详细跳转小程序页面,不填就没有查看详情
        map.put("page", pageUrl);
        //发送用户的open_id
        map.put("touser", openId);
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        map.put("miniprogram_state", miniprogramState);
        //编码格式
        map.put("lang", "zh_CN");

        map.put("data", data);

        String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken + "&a=1";
        Map<String, String> param = new HashMap<>();
        param.put("access_token", accessToken);
        String post = HttpClientUtil.sendPostJsonRepeatProxy(sendUrl, JSONObject.toJSONString(map), proxyUrl, 80, isUseProxy);
        if (!JSONObject.parseObject(post).getInteger("errcode").equals(0)) {
            logger.info("发送小程序通知失败");
            String errMsg = JSONObject.parseObject(post).getString("errmsg");
            logger.info(errMsg);
            if (errMsg.contains("access_token expired rid")) {
                logger.info("access_token过期，重新获取");
            }
        } else {
            logger.info("成功发送小程序通知post:{}", post);
        }
        System.out.println(post);
    }

    @Override
    public Object addressIdentify(String addressText) {
        Map map = new HashMap();
        map.put("ak", splitAddressAk);
        map.put("syscode", syscode);
        map.put("addresstext", addressText);
        String post = restTemplate.postForObject(splitAddressUrl, map, String.class);
        if (!JSONObject.parseObject(post).getString("status").equals("0")) {
            throw new RuntimeException("接口网络不通");
        }
        if (!JSONObject.parseObject(JSONObject.parseObject(post).getString("result")).getInteger("code").equals(0)) {
            logger.info(JSONObject.parseObject(JSONObject.parseObject(post).getString("result")).getString("message"));
            throw new RuntimeException("地址解析失败：" + JSONObject.parseObject(JSONObject.parseObject(post).getString("result")).getString("message"));
        }
        return JSONObject.parseObject(post);
    }

    @Override
    public Object checkSign(String qkPhone, String sign, Long timeStamp, String nonce) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String params = "        {\n" +
                "            \"body\":{\n" +
                "            \"qkPhone\":\"" + qkPhone + "\",\n" +
                "                    \"projectId\":" + cloudProjectId + ",\n" +
                "                    \"externalUrl\":null,\n" +
                "                    \"idcard\":null,\n" +
                "                    \"workNumber\":null,\n" +
                "                    \"qkName\":null\n" +
                "        },\n" +
                "            \"key\":\"" + cloudKey + "\",\n" +
                "                \"nonce\":\"" + nonce + "\",\n" +
                "                \"timeStamp\":" + timeStamp + ",\n" +
                "                \"sign\":\"" + sign + "\"\n" +
                "        }";
        String post = HttpClientUtil.sendPostJsonRepeatProxy(cloudTestUrl + "/api/externalRegister/isMakerSign", params, xcyProxyUrl, 80, isUseProxy);
        logger.info("rs:" + post);
        JSONObject result = JSONObject.parseObject(post);
        logger.info(result.toString());
        return result;
    }

    @Override
    public Object getSign(String qkPhone, String sign, Long timeStamp, String nonce, String userId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String params = "{\n" +
                "    \"body\": {\n" +
                "        \"qkPhone\": \"" + qkPhone + "\",\n" +
                "        \"projectId\": " + cloudProjectId + ",\n" +
                "        \"externalUrl\": " + "\"" + h5Url + "/index.html#/pages/promotionPage/promotionCash?id=" + userId + "\"" + ",\n" +
                "        \"workNumber\": null,\n" +
                "        \"qkName\": null,\n" +
                "        \"asynUrl\": \"" + callbackUrl + "home/wx/sign-record\",\n" +
                "        \"skipFlag\": 2,\n" +
                "        \"remark\": null\n" +
                "    },\n" +
                "    \"key\": \"" + cloudKey + "\",\n" +
                "    \"nonce\": \"" + nonce + "\",\n" +
                "    \"timeStamp\": " + timeStamp + ",\n" +
                "    \"sign\": \"" + sign + "\"\n" +
                "}";
        String post = HttpClientUtil.sendPostJsonRepeatProxy(cloudTestUrl + "/api/externalRegister/transferExternalRegister", params, xcyProxyUrl, 80, isUseProxy);
        JSONObject result = JSONObject.parseObject(post);
        return result;
    }

    @Override
    public Object getSignInfo(String qkPhone, String sign, Long timeStamp, String nonce) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String params = "{\n" +
                "  \"body\": {\n" +
                "    \"projectId\": " + cloudProjectId + ",\n" +
                "    \"qkPhone\": \"" + qkPhone + "\"\n" +
                "  },\n" +
                "  \"key\": \"" + cloudKey + "\",\n" +
                "  \"nonce\": \"" + nonce + "\",\n" +
                "  \"timeStamp\": " + timeStamp + ",\n" +
                "  \"sign\": \"" + sign + "\"\n" +
                "}\n";
        String post = HttpClientUtil.sendPostJsonRepeatProxy(cloudTestUrl + "/api/externalRegister/selectQingkeByPhone", params, xcyProxyUrl, 80, isUseProxy);
        JSONObject result = JSONObject.parseObject(post);
        return result;
    }

    @Override
    public Object wxPay(String params) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> response;
//        response = restTemplate.postForEntity(cloudTestUrl + "/api/merchant/pay", entity, JSONObject.class);
        String post = HttpClientUtil.sendPostJsonRepeatProxy(cloudTestUrl + "/api/merchant/pay", params, xcyProxyUrl, 80, isUseProxy);
//        JSONObject result = response.getBody();
        JSONObject result = JSONObject.parseObject(post);
//        JSONObject jsonObject = JSONObject.parseObject("{\n" +
//                "    \"requestId\": null,\n" +
//                "    \"success\": true,\n" +
//                "    \"errorCode\": null,\n" +
//                "    \"date\": \"2020-11-17 18:08:31\",\n" +
//                "    \"timestamp\": 1605607711793,\n" +
//                "    \"version\": \"1.0\",\n" +
//                "    \"errorMessage\": null,\n" +
//                "    \"obj\": null\n" +
//                "}");
        return result;
    }
}
